<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>6-自定义事件机制</title>
  </head>
  <body>
    <script>
      class Event {
        constructor() {
          /*
        * this.events = {
          click: [f1,f2,f3],
          mousemove: [f1,f2,f3]
        }
        */
          this.events = {};
        }
        // 添加相应的事件处理
        on(evnet, fn) {
          if (!this.events[evnet]) {
            this.events[evnet] = [];
          }
          this.events[evnet].push(fn);
        }

        // 删除相应的事件处理
        off(evnet, fn) {
          if (this.events[evnet]) {
            this.events[evnet] = this.events[evnet].filter(
              (item) => fn != item
            );
          }
        }

        // 触发相应的事件处理
        dispatch(event, ...arg) {
          if (this.events[event]) {
            this.events[event].forEach((item) => {
              item.call(this, ...arg); // 从window => 指向实例化对象
            });
          }
        }
      }

      let event = new Event();
      let f1 = () => {
        console.log(1);
      };
      event.on("dragstart", f1);
      let f2 = () => {
        console.log(2);
      };
      event.on("dragstart", f2);
      document.onclick = function(){
        // event.off("dragstart", f2);
        // console.log(event);
        
        event.dispatch("dragstart");
      };
      console.log(event);
    </script>
  </body>
</html>
